package com.example.controller;

import com.example.util.FtlWordUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
public class FtlToWordController {
    @RequestMapping("ftl")
    public ResponseEntity<byte[]> index(String type,String name) {
        ByteArrayOutputStream baos = null;
        String fileName = "mytest";
        if(null != name){
            fileName = name;
        }
        try {
            String templateName = "dubandan";
            Map<String,Object> map = FtlWordUtil.getDbdTest();
            if("1".equals(type)){
                templateName = "yujingdan";
                map = FtlWordUtil.getYJDTest();
            }
            FtlWordUtil.createWord(map, templateName, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            return null;
        }
        baos = FtlWordUtil.readFileWord(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",
                new String((fileName + ".doc").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        byte[] bo = baos.toByteArray();
        System.out.println("return");
        return new ResponseEntity<>(bo, headers, HttpStatus.CREATED);
    }
}
